package com.example.springboot_shiro.shiro.realms;

import com.example.springboot_shiro.domain.test.User;
import com.example.springboot_shiro.domain.test.Role;
import com.example.springboot_shiro.service.UserService;
import com.example.springboot_shiro.utils.ApplicationContextUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.CollectionUtils;

import java.util.List;

/**
 * @author: lqy
 * @date: 2021/9/8 15:17
 * @description:
 */
public class MyRealm extends AuthorizingRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取身份信息
        String principal = (String) principalCollection.getPrimaryPrincipal();
        //根据住身份信息获取角色和权限信息
        //授权角色信息
        UserService userService = (UserService) ApplicationContextUtils.getBean("userServiceImpl");
        List<Role> roleList = userService.findRolesByUserId(principal);
        if (!CollectionUtils.isEmpty(roleList)) {
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            roleList.forEach(role -> {
                simpleAuthorizationInfo.addRole(role.getRoleName());
                //权限信息
                /*if(!CollectionUtils.isEmpty(role.getAuthorities())){
                    role.getAuthorities().forEach(authority -> {
                        simpleAuthorizationInfo.addStringPermission(authority.getAuthorityName());
                    });
                }*/
            });
            return simpleAuthorizationInfo;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //根据身份信息
        String principal = (String) authenticationToken.getPrincipal();
        //在工厂中获取service对象
        UserService userService = (UserService) ApplicationContextUtils.getBean("userServiceImpl");
        User user = userService.findByUserName(principal);
        System.out.println(user.toString());
        if (StringUtils.isNotEmpty(user.getUsername()) && StringUtils.isNotEmpty(user.getPassword())) {
            return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName());
        }
        return null;
    }
}
